﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;

namespace lhservice.common
{
  public class UploadHelper
  {

    /// <summary>
    /// 保存上传图片 的返回
    /// </summary>
    public class ReturnForSaveImg {
      public Boolean IsSuccess { get; set; }
      public string Url { get; set; }
      public string media_id { get; set; }
    }

    /// <summary>
    /// 上传微信图片素材 返回对象
    /// </summary>
    public class ReturnForUploadMediaOnMp {
      public string type { get; set; }
      public string media_id { get; set; }
      public long created_at { get; set; }
      public List<string> item { get; set; }
    }

    /// <summary>
    /// 将Base64字符串转换为Image对象
    /// </summary>
    /// <param name="base64Str">base64字符串</param>
    /// <returns></returns>
    public static Bitmap Base64StrToImage(string base64Str)
    {
      Bitmap bitmap = null;

      try
      {
        byte[] arr = Convert.FromBase64String(base64Str);
        MemoryStream ms = new MemoryStream(arr);
        Bitmap bmp = new Bitmap(ms);
        ms.Close();
        bitmap = bmp;
      }
      catch (Exception ex)
      {

      }

      return bitmap;
    }

    /// <summary>
    /// 将Base64字符串保存为本地图片
    /// </summary>
    /// <param name="base64Str">base64字符串</param>
    /// <returns></returns>
    public static ReturnForSaveImg Base64SaveAsLocalImg(string base64Str)
    {     
      var suffix = base64Str.Split(";base64")[0].Split("/")[1];
      var imgName = $"{Guid.NewGuid()}.{suffix}";
      var absPath = Path.Combine("uploads/images/", imgName);
      var savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", absPath);
      var ret = true;
      try
      {
        var bitmap = Base64StrToImage(base64Str.Split(";base64,")[1]);
        if (bitmap != null)
        {            
          var suffixName = suffix == "png" ? ImageFormat.Png :
              suffix == "jpg" || suffix == "jpeg" ? ImageFormat.Jpeg :
              suffix == "bmp" ? ImageFormat.Bmp :
              suffix == "gif" ? ImageFormat.Gif : ImageFormat.Jpeg;          
          var bmpNew = new Bitmap(bitmap);
          bmpNew.Save(savePath, suffixName);
          bmpNew.Dispose();
          bitmap.Dispose();
        }
        else
        {
          ret = false;
        }
      }
      catch (Exception ex)
      {
        ret = false;
      }

      var res = new ReturnForSaveImg
      {
        IsSuccess = ret,
        Url = $"{PublicHelper.Host}{absPath}",
        media_id = MpUploadMedia(savePath)
      };   
      
      return res;
    }


    public static string DownloadImgFromMpUrl(string url) {
      var filename = $"{Guid.NewGuid()}.png";
      var absPath = Path.Combine("uploads/images/", filename);
      var savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", absPath);

      //savePath = sWebRootFolder + savePath;
      ////无夹创建
      //if (!Directory.Exists(savePath))
      //{
      //  Directory.CreateDirectory(savePath);
      //}
      WebClient wClient = new WebClient();
      //下载文件
      wClient.DownloadFile(url, savePath);
      return $"{PublicHelper.Host}{absPath}";
    }



    /// <summary>
    /// 上传微信素材 
    /// </summary>
    /// <param name="path"> 本地图片地址</param>
    /// <returns></returns>
    public static string MpUploadMedia(string path)
    {
      var token = MpToken.GetToken();
      string url = $"https://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type=image";
      //path = "D:\\source\\lh-service-api\\lhservice\\wwwroot\\uploads\\images\\test.png";

      // 设置参数
      HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
      CookieContainer cookieContainer = new CookieContainer();
      request.CookieContainer = cookieContainer;
      request.AllowAutoRedirect = true;
      request.Method = "POST";
      string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
      request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
      byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
      byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

      int pos = path.LastIndexOf("\\");
      string fileName = path.Substring(pos + 1);

      //请求头部信息
      StringBuilder sbHeader = new StringBuilder($"Content-Disposition:form-data;name=\"file\";filename=\"{fileName}\"\r\nContent-Type:application/octet-stream\r\n\r\n");
      byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

      FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
      byte[] bArr = new byte[fs.Length];
      fs.Read(bArr, 0, bArr.Length);
      fs.Close();

      Stream postStream = request.GetRequestStream();
      postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
      postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
      postStream.Write(bArr, 0, bArr.Length);
      postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
      postStream.Close();

      HttpWebResponse response = request.GetResponse() as HttpWebResponse;
      Stream instream = response.GetResponseStream();
      StreamReader sr = new StreamReader(instream, Encoding.UTF8);
      string content = sr.ReadToEnd();
      //return { "type":"image","media_id":"I5_dbJPBWmweT_aAnp0A-S4bmiHIsLs_ZgH4rxKuunBn0XL18yqqCy_rceSFtAOi","created_at":1620790816,"item":[]  
      ReturnForUploadMediaOnMp res = JsonConvert.DeserializeObject<ReturnForUploadMediaOnMp>(content);          
      return res.media_id;
    }
  }
}
